<html>
<head>
    <script type="text/javascript">var oldAlert = window.alert, gMess; window.alert = function(message) {gMess = message; return true;};</script>
    <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script>
    <script type="text/javascript">window.alert = oldAlert;</script>
<script src="../OLLoader.js"></script>
  <script type="text/javascript">
    // turn off animation frame handling, so we can check img urls in tests
    delete OpenLayers.Layer.Grid.prototype.queueTileDraw;

    var isMozilla = (navigator.userAgent.indexOf("compatible") == -1);
    var layer;

    var name = 'Test Layer';
    var url = "http://octo.metacarta.com/cgi-bin/mapserv";
    var params = { map: '/mapdata/vmap_wms.map',
                   layers: 'basic',
                   format: 'image/jpeg'};

    function test_Layer_WMS_constructor (t) {
        t.plan( 15 );

        var trans_format = "image/png";
        if (OpenLayers.Util.alphaHack()) { trans_format = "image/gif"; }

        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        layer = new OpenLayers.Layer.WMS(name, url, params);
        t.ok( layer instanceof OpenLayers.Layer.WMS, "new OpenLayers.Layer.WMS returns object" );
        t.eq( layer.url, "http://octo.metacarta.com/cgi-bin/mapserv", "layer.url is correct (HTTPRequest inited)" );
        t.eq( layer.params.MAP, "/mapdata/vmap_wms.map", "params passed in correctly uppercased" );

        t.eq( layer.params.SERVICE, "WMS", "default params correclty uppercased and copied");

        t.eq(layer.isBaseLayer, true, "no transparency setting, wms is baselayer");

        params.TRANSPARENT = "true";
        var layer2 = new OpenLayers.Layer.WMS(name, url, params);
        t.eq(layer2.isBaseLayer, false, "transparency == 'true', wms is not baselayer");

        params.TRANSPARENT = "TRUE";
        var layer3 = new OpenLayers.Layer.WMS(name, url, params);
        t.eq(layer3.isBaseLayer, false, "transparency == 'TRUE', wms is not baselayer");
        t.eq(layer3.params.FORMAT, trans_format, "transparent = TRUE causes non-image/jpeg format");

        params.TRANSPARENT = "TRuE";
        var layer4 = new OpenLayers.Layer.WMS(name, url, params);
        t.eq(layer4.isBaseLayer, false, "transparency == 'TRuE', wms is not baselayer");
        t.eq(layer4.params.FORMAT, trans_format, "transparent = TRuE causes non-image/jpeg format");

        params.TRANSPARENT = true;
        var layer5 = new OpenLayers.Layer.WMS(name, url, params);
        t.eq(layer5.isBaseLayer, false, "transparency == true, wms is not baselayer");
        t.eq(layer5.params.FORMAT, trans_format, "transparent = true causes non-image/jpeg format");

        params.TRANSPARENT = false;
        var layer6 = new OpenLayers.Layer.WMS(name, url, params);
        t.eq(layer6.isBaseLayer, true, "transparency == false, wms is baselayer");

        params.TRANSPARENT = true;
        var layer7 = new OpenLayers.Layer.WMS(name, url, params, {noMagic: true});
        t.eq(layer7.params.FORMAT, "image/jpeg", "When using noMagic true image/jpeg will not be automagically switched to image/png or image/gif if transparent");

        params.TRANSPARENT = true;
        var layer8 = new OpenLayers.Layer.WMS(name, url, params, {noMagic: true});
        t.eq(layer8.isBaseLayer, true, "When using noMagic then transparent means the wms layer is not automagically changed to not being a baselayer");

        params.TRANSPARENT = false;

    }

    function test_Layer_WMS_addtile (t) {
        t.plan( 6 );

        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        layer = new OpenLayers.Layer.WMS(name, url, params);
        var map = new OpenLayers.Map('map', {tileManager: null});
        map.addLayer(layer);
        var pixel = new OpenLayers.Pixel(5,6);
        var tile = layer.addTile(new OpenLayers.Bounds(1,2,3,4), pixel);
        tile.draw();

        var img = tile.imgDiv;
        var tParams = OpenLayers.Util.extend({},
                        OpenLayers.Util.upperCaseObject(params));
        tParams = OpenLayers.Util.extend(tParams, {
            BBOX: [1,2,3,4],
            WIDTH: "256", HEIGHT: "256"
        });
        t.eq( tile.url,
             layer.getFullRequestString(tParams),
             "image src is created correctly via addtile" );
        t.eq( tile.getTile().style.top, "6px", "image top is set correctly via addtile" );
        t.eq( tile.getTile().style.left, "5px", "image top is set correctly via addtile" );

        var firstChild = layer.div.firstChild;
        t.eq( firstChild.nodeName.toLowerCase(), "img", "div first child is an image object" );
        t.ok( firstChild == img, "div first child is correct image object" );
        t.eq( tile.position.toString(), "x=5,y=6", "Position of tile is set correctly." );
        map.destroy();
    }

    function test_Layer_WMS_bboxEncoding (t) {
        t.plan( 6 );

        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        layer = new OpenLayers.Layer.WMS(name, url, params, {encodeBBOX:true});
        var map = new OpenLayers.Map('map', {tileManager: null});
        map.addLayer(layer);
        var pixel = new OpenLayers.Pixel(5,6);
        var tile = layer.addTile(new OpenLayers.Bounds(1,2,3,4), pixel);
        tile.draw();

        var img = tile.imgDiv;
        var tParams = OpenLayers.Util.extend({},
                        OpenLayers.Util.upperCaseObject(params));
        tParams = OpenLayers.Util.extend(tParams, {
            BBOX: "1,2,3,4",
            WIDTH: "256", HEIGHT: "256"
        });
        t.eq( tile.url,
             layer.getFullRequestString(tParams),
             "image src is created correctly via addtile" );
        t.eq( tile.getTile().style.top, "6px", "image top is set correctly via addtile" );
        t.eq( tile.getTile().style.left, "5px", "image top is set correctly via addtile" );

        var firstChild = layer.div.firstChild;
        t.eq( firstChild.nodeName.toLowerCase(), "img", "div first child is an image object" );
        t.ok( firstChild, img, "div first child is correct image object" );
        t.eq( tile.position.toString(), "x=5,y=6", "Position of tile is set correctly." );
        map.destroy();
    }

    function test_Layer_WMS_inittiles (t) {
        t.plan( 2 );
        var map = new OpenLayers.Map('map');
        layer = new OpenLayers.Layer.WMS(name, url, params, {buffer:2});
        map.addLayer(layer);
        map.setCenter(new OpenLayers.LonLat(0,0),5);
        t.eq( layer.grid.length, 8, "Grid rows is correct." );
        t.eq( layer.grid[0].length, 7, "Grid cols is correct." );
        map.destroy();
    }

    function test_Layer_WMS_clone (t) {
        t.plan(4);

        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        var options = {tileSize: new OpenLayers.Size(500,50)};
        var map = new OpenLayers.Map('map', options);
        layer = new OpenLayers.Layer.WMS(name, url, params);
        map.addLayer(layer);

        layer.grid = [ [6, 7],
                       [8, 9]];

        var clone = layer.clone();

        t.ok( clone.grid != layer.grid, "clone does not copy grid");

        t.ok( clone.tileSize.equals(layer.tileSize), "tileSize correctly cloned");

        layer.tileSize.w += 40;

        t.eq( clone.tileSize.w, 500, "changing layer.tileSize does not change clone.tileSize -- a fresh copy was made, not just copied reference");

        t.eq( clone.alpha, layer.alpha, "alpha copied correctly");

        layer.grid = null;
        map.destroy();
    }

    function test_Layer_WMS_isBaseLayer(t) {
        t.plan(3);

        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        layer = new OpenLayers.Layer.WMS(name, url, params);
        t.ok( layer.isBaseLayer, "baselayer is true by default");

        var newParams = OpenLayers.Util.extend({}, params);
        newParams.transparent = "true";
        layer = new OpenLayers.Layer.WMS(name, url, newParams);
        t.ok( !layer.isBaseLayer, "baselayer is false when transparent is set to true");

        layer = new OpenLayers.Layer.WMS(name, url, params, {isBaseLayer: false});
        t.ok( !layer.isBaseLayer, "baselayer is false when option is set to false" );
    }

    function test_Layer_WMS_mergeNewParams (t) {
        t.plan( 4 );

        var map = new OpenLayers.Map("map");
        var url = "http://octo.metacarta.com/cgi-bin/mapserv";
        layer = new OpenLayers.Layer.WMS(name, url, params);

        var newParams = { layers: 'sooper',
                          chickpeas: 'image/png'};

        map.addLayer(layer);
        map.zoomToMaxExtent();

        layer.redraw = function() {
            t.ok(true, "layer is redrawn after new params merged");
        }

        layer.mergeNewParams(newParams);

        t.eq( layer.params.LAYERS, "sooper", "mergeNewParams() overwrites well");
        t.eq( layer.params.CHICKPEAS, "image/png", "mergeNewParams() adds well");

        newParams.CHICKPEAS = 151;

        t.eq( layer.params.CHICKPEAS, "image/png", "mergeNewParams() makes clean copy of hashtable");
        map.destroy();
    }

    function test_Layer_WMS_getFullRequestString (t) {


        t.plan( 4 );
        var map = new OpenLayers.Map('map');
        map.projection = "xx";
        var tUrl = "http://octo.metacarta.com/cgi-bin/mapserv";
        var tParams = { layers: 'basic',
                   format: 'image/png'};
        var tLayer = new OpenLayers.Layer.WMS(name, tUrl, tParams);
        map.addLayer(tLayer);
        var str = tLayer.getFullRequestString();
        var tParams = {
            LAYERS: "basic", FORMAT: "image/png", SERVICE: "WMS",
            VERSION: "1.1.1", REQUEST: "GetMap", STYLES: "",
            SRS: "xx"
        };
        t.eq(str,
             tUrl + "?" + OpenLayers.Util.getParameterString(tParams),
             "getFullRequestString() adds SRS value");

        map.removeLayer(tLayer);
        tLayer.projection = "none";
        map.addLayer(tLayer);
        str = tLayer.getFullRequestString();
        delete tParams['SRS'];
        t.eq(str,
             tUrl + "?" + OpenLayers.Util.getParameterString(tParams),
             "getFullRequestString() by default does *not* add SRS value if projection is 'none'");
        map.destroy();
        
        map = new OpenLayers.Map("map", {projection: "EPSG:4326"});
        var layerProj = new OpenLayers.Projection("FOO", {
            equals: function() {return true},
            getCode: function() {return "FOO"}
        });
        tLayer = new OpenLayers.Layer.WMS(name, tUrl, tParams, {projection: layerProj});
        map.addLayer(tLayer);
        str = tLayer.getFullRequestString();
        tParams.SRS = "FOO";
        t.eq(str,
             tUrl + "?" + OpenLayers.Util.getParameterString(tParams),
             "getFullRequestString() uses the layer projection if it equals the map projection");
        map.destroy();

        map = new OpenLayers.Map("map", {projection: "EPSG:4326"});
        map.addLayer(new OpenLayers.Layer(null, {isBaseLayer: true}));
        tLayer = new OpenLayers.Layer.WMS(name, tUrl);
        tLayer.map = map;
        var error;
        try {
            tLayer.getFullRequestString();
            error = false;
        } catch(err) {
            error = true;
    }
        t.ok(!error, "no error on getFullRequestString if layer has no projection");
        map.destroy();

    }

    function test_setOpacity(t) {
        t.plan(1);

        var layer = new OpenLayers.Layer.WMS(
            null, "/bogus/wms", {layers: "mylayer"}
        );
        var map = new OpenLayers.Map("map");
        map.addLayer(layer);
        
        map.zoomToMaxExtent();
        
        layer.setOpacity(0.5);
        t.delay_call(1, function() {
            t.eq(parseFloat(layer.div.firstChild.style.opacity), 0.5, "opacity set");
            map.destroy();
        });
    }


    function test_Layer_WMS_noGutters (t) {
        t.plan(2);
        var map = new OpenLayers.Map('map');
        var layer = new OpenLayers.Layer.WMS("no gutter layer", url, params, {gutter: 0});
        map.addLayer(layer);
        map.setCenter(new OpenLayers.LonLat(0,0), 5);
        var tile = layer.grid[0][0];
        var request = layer.getURL(tile.bounds);
        var args = OpenLayers.Util.getParameters(request);
        t.eq(parseInt(args['WIDTH']),
             tile.size.w,
             "layer without gutter requests images that are as wide as the tile");
        t.eq(parseInt(args['HEIGHT']),
             tile.size.h,
             "layer without gutter requests images that are as tall as the tile");

        layer.destroy();
        map.destroy();
    }

    function test_Layer_WMS_gutters (t) {
        t.plan(2);
        var gutter = 15;
        var map = new OpenLayers.Map('map');
        var layer = new OpenLayers.Layer.WMS("gutter layer", url, params, {gutter: gutter});
        map.addLayer(layer);
        map.setCenter(new OpenLayers.LonLat(0,0), 5);
        var tile = layer.grid[0][0];
        var request = layer.getURL(tile.bounds);
        var args = OpenLayers.Util.getParameters(request);
        t.eq(parseInt(args['WIDTH']),
             tile.size.w + (2 * gutter),
             "layer with gutter requests images that are wider by twice the gutter");
        t.eq(parseInt(args['HEIGHT']),
             tile.size.h + (2 * gutter),
             "layer with gutter requests images that are taller by twice the gutter");

        layer.destroy();
        map.destroy();

    }

    function test_maxExtent(t) {
        t.plan(5);
        
        var layer = new OpenLayers.Layer.WMS(
            null, "http://example.com/wms", 
            {layers: "foo"}, 
            {maxExtent: [-180, 0, 0, 90]}
        );
        
        t.ok(layer.maxExtent instanceof OpenLayers.Bounds, "(array) bounds instance");
        t.eq(layer.maxExtent.left, -180, "(array) bounds left");
        t.eq(layer.maxExtent.bottom, 0, "(array) bounds left");
        t.eq(layer.maxExtent.right, 0, "(array) bounds right");
        t.eq(layer.maxExtent.top, 90, "(array) bounds top");
        
        layer.destroy();
    }

    function test_minExtent(t) {
        t.plan(5);
        
        var layer = new OpenLayers.Layer.WMS(
            null, "http://example.com/wms", 
            {layers: "foo"}, 
            {minExtent: [-180, 0, 0, 90]}
        );
        
        t.ok(layer.minExtent instanceof OpenLayers.Bounds, "(array) bounds instance");
        t.eq(layer.minExtent.left, -180, "(array) bounds left");
        t.eq(layer.minExtent.bottom, 0, "(array) bounds left");
        t.eq(layer.minExtent.right, 0, "(array) bounds right");
        t.eq(layer.minExtent.top, 90, "(array) bounds top");
        
        layer.destroy();
    }

    function test_tileOrigin(t) {
        t.plan(4);
        
        var dummy = new OpenLayers.Layer(null, {isBaseLayer: true});
        var unconstrained = new OpenLayers.Layer.WMS(
            null, "http://example.com/wms", 
            {layers: "unconstrained"}, 
            {isBaseLayer: false, buffer: 0}
        );
        var constrained = new OpenLayers.Layer.WMS(
            null, "http://example.com/wms-c", 
            {layers: "constrained"}, 
            {buffer: 0, isBaseLayer: false, tileOrigin: new OpenLayers.LonLat(-180, -90)}
        );
        var map = new OpenLayers.Map({
            div: "map",
            maxExtent: new OpenLayers.Bounds(-185, -95, 185, 95),
            maxResolution: 1.40625,
            layers: [dummy, unconstrained, constrained],
            center: new OpenLayers.LonLat(0, 0),
            zoom: 1
        });
        
        t.eq(unconstrained.grid[1][0].bounds.bottom, -95, "unconstrained bottom correct");
        t.eq(unconstrained.grid[1][0].bounds.left, -185, "unconstrained left correct");
        t.eq(constrained.grid[1][0].bounds.bottom, -90, "constrained bottom correct");
        t.eq(constrained.grid[1][0].bounds.left, -180, "constrained left correct");
        
        map.destroy();
        
    }

    function test_Layer_WMS_destroy (t) {

        t.plan( 1 );

        var map = new OpenLayers.Map('map');
        layer = new OpenLayers.Layer.WMS(name, url, params);
        map.addLayer(layer);

        map.setCenter(new OpenLayers.LonLat(0,0), 5);

        //grab a reference to one of the tiles
        var tile = layer.grid[0][0];

        layer.destroy();

    // checks to make sure superclass (grid) destroy() was called

        t.ok( layer.grid == null, "grid set to null");
    }

    function test_customProjection(t) {
        t.plan(1);
        var map = new OpenLayers.Map('map', {
            units: 'm', 
            projection: new OpenLayers.Projection('EPSG:28992'),
            maxExtent: new OpenLayers.Bounds(0, 300000, 300000, 6250000)
        });
        var layer = new OpenLayers.Layer.WMS(null, url, {layers: 'mylayer', version: '1.3.0'});
        map.addLayer(layer);
        var error = false;
        try {
            map.setCenter(new OpenLayers.LonLat(100000,300000), 5);
        } catch(err) {
            error = true;
        }
        t.ok(!error, "no error on getURL if layer has a custom projection and no defaults defined");
        layer.destroy();
        map.destroy();
    }

    function test_Layer_WMS_v13(t) {

        t.plan(6);

        var lon = 5;
        var lat = 40;
        var zoom = 5;
        var map = new OpenLayers.Map( 'map' );
        var layer = new OpenLayers.Layer.WMS(
            "OpenLayers WMS",
            "http://myserver.org/wms?",
            {layers: 'mylayer', version: '1.3.0'},
            {singleTile: true}
        );
        map.addLayer(layer);
        map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

        var url = layer.getURL(map.getExtent());
        var params = url.split("&");
        var bbox;
        for (var i=0, len=params.length; i<len; i++) {
            var param = params[i];
            var a = param.split('=');
            if (a[0] === 'BBOX') {
                bbox = a[1];
                break;
            }
        }

        t.eq(layer.params.CRS, "EPSG:4326", "In WMS 1.3 SRS is now CRS");
        t.eq(bbox, "27.9150390625,-5.986328125,52.0849609375,15.986328125", "Axis sequence is lat lon for EPSG:4326 in WMS 1.3.0");

        var layer2 = new OpenLayers.Layer.WMS(
            "OpenLayers WMS",
            "http://myserver.org/wms?",
            {layers: 'mylayer', version: '1.1.1'},
            {singleTile: true}
        );
        map.addLayer(layer2);

        var url = layer2.getURL(map.getExtent());
        var params = url.split("&");
        var bbox;
        for (var i=0, len=params.length; i<len; i++) {
            var param = params[i];
            var a = param.split('=');
            if (a[0] === 'BBOX') {
                bbox = a[1];
                break;
            }
        }

        t.eq(layer2.params.SRS, "EPSG:4326", "In WMS 1.1.1 parameter is called SRS");
        t.eq(bbox, "-5.986328125,27.9150390625,15.986328125,52.0849609375", "Axis sequence is lon lat for EPSG:4326 in WMS 1.1.1");

        map.destroy();

        // CRS:84 has normal axis sequence (lon lat)
        var map = new OpenLayers.Map( 'map', {projection: 'CRS:84'} );
        var layer = new OpenLayers.Layer.WMS(
            "OpenLayers WMS",
            "http://myserver.org/wms?",
            {layers: 'mylayer', version: '1.3.0'},
            {singleTile: true}
        );
        map.addLayer(layer);
        map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

        var url = layer.getURL(map.getExtent());
        var params = url.split("&");
        var bbox, exceptions;
        for (var i=0, len=params.length; i<len; i++) {
            var param = params[i];
            var a = param.split('=');
            if (a[0] === 'EXCEPTIONS') {
                exceptions = a[1];
            }
            if (a[0] === 'BBOX') {
                bbox = a[1];
            }
        }

        t.eq(exceptions, "INIMAGE", "If not set, EXCEPTIONS should be INIMAGE for WMS 1.3");
        t.eq(bbox, "-5.986328125,27.9150390625,15.986328125,52.0849609375", "Axis sequence for CRS:84 is lon lat");

        map.destroy();

    }
    
    function test_transparent(t) {
        t.plan(5);
        var map = new OpenLayers.Map("map", {allOverlays: true});
        var layer = new OpenLayers.Layer.WMS(
            "OpenLayers WMS",
            "http://myserver.org/wms?",
            {layers: 'mylayer', transparent: true}
        );
        map.addLayer(layer);

        t.eq(typeof layer.params.TRANSPARENT, "boolean", "transparent param is boolean");
        t.ok(layer.getFullRequestString({}).indexOf("TRANSPARENT=TRUE") != -1, "Boolean transparent param value is uppercase TRUE");
        layer.mergeNewParams({transparent: false});
        t.ok(layer.getFullRequestString({}).indexOf("TRANSPARENT=FALSE") != -1, "Boolean transparent param value is uppercase FALSE");

        layer.mergeNewParams({transparent: "true"});
        t.eq(typeof layer.params.TRANSPARENT, "string", "transparent param is string");
        t.ok(layer.getFullRequestString({}).indexOf("TRANSPARENT=true") != -1, "transparent param value passed as provided if String");
        
        map.destroy();
    }
    
    function test_tileBounds(t) {
        t.plan(3);
        
        var map = new OpenLayers.Map("map", {projection: "EPSG:3857", zoomMethod: null});
        var layer = new OpenLayers.Layer.WMS("wms", "../../img/blank.gif");
        map.addLayer(layer);
        map.setCenter([0, 0], 1);
        map.pan(2, -100);
        map.zoomIn();
        t.eq(layer.grid[1][0].bounds, new OpenLayers.Bounds(-10018754.17, 0, 0, 10018754.17), "no floating point errors after zooming");
        map.setCenter([0, 0], 14);
        var bounds = layer.grid[0][0].bounds.clone();
        map.pan(260, 520);
        map.pan(-260, -520);
        t.eq(layer.grid[0][0].bounds, bounds, "no floating point errors after dragging back and forth");
        t.eq(bounds.right, 0, "0 is 0, and not some super small number");
        
        map.destroy();
    }


  </script>
</head>
<body>
<div id="map" style="width:500px;height:550px"></div>
</body>
</html>
